package com.xiashitech.agent.instrumentation.apachehttpclient.v2v3.inst;

import static io.opentelemetry.javaagent.extension.matcher.AgentElementMatchers.extendsClass;
import static io.opentelemetry.javaagent.extension.matcher.AgentElementMatchers.hasClassesNamed;
import static net.bytebuddy.matcher.ElementMatchers.isMethod;
import static net.bytebuddy.matcher.ElementMatchers.named;
import static net.bytebuddy.matcher.ElementMatchers.takesArgument;
import static net.bytebuddy.matcher.ElementMatchers.takesArguments;

import com.xiashitech.agent.cache.status.CacheStatus;
import com.xiashitech.agent.config.StartConfig;
import com.xiashitech.agent.instrumentation.apachehttpclient.common.v2v3.HttpClientHeaderGetter;
import com.xiashitech.agent.instrumentation.base.propagator.W3CReentryBaggagePropagator;
import com.xiashitech.agent.instrumentation.bridge.Java8Bridge;
import com.xiashitech.agent.utils.DurationPrinter;
import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;
import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
import org.apache.commons.httpclient.HttpMethod;

public class ApacheHttpClientv2v3Instrumentation implements TypeInstrumentation {
  @Override
  public ElementMatcher<ClassLoader> classLoaderOptimization() {
    return hasClassesNamed("org.apache.commons.httpclient.HttpClient");
  }

  @Override
  public ElementMatcher<TypeDescription> typeMatcher() {
    return extendsClass(named("org.apache.commons.httpclient.HttpClient"));
  }

  @Override
  public void transform(TypeTransformer transformer) {
    transformer.applyAdviceToMethod(
        isMethod()
            .and(named("executeMethod"))
            .and(takesArguments(3))
            .and(takesArgument(1, named("org.apache.commons.httpclient.HttpMethod"))),
        this.getClass().getName() + "$ExecuteMethodAdvice");
  }

  @SuppressWarnings("unused")
  public static class ExecuteMethodAdvice {
    @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
    public static void methodExit(
        @Advice.Argument(1) HttpMethod httpMethod,
        @Advice.Thrown Throwable throwable) {
      DurationPrinter durationPrinter = new DurationPrinter("ApacheHttpClientv2v3Instrumentation");
      if(CacheStatus.cannotRun()) {
        return;
      }
      try {
        W3CReentryBaggagePropagator.getInstance().extract(Java8Bridge.currentForXSContext(), httpMethod, HttpClientHeaderGetter.INSTANCE).makeCurrent();
      } catch (Throwable e) {
        StartConfig.throwableStackPrinter(e);
      }
      durationPrinter.printElapseDuration("ExecuteMethodAdvice b");
    }
  }
}
